package com.techwells.taco.widget;

import java.io.UnsupportedEncodingException;

import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

import com.techwells.taco.utils.ToastUtils;


/**
 * edittext监听器，用于限制字数，如果字数超过，则自动舍弃，并通过toast提示
 * 
 */
public class EditTextWatcher implements TextWatcher {

	private static final String TAG = "EditTextWatcher";

	private CharSequence temp;
	private int selectionStart;
	private int selectionEnd;
	// 字数限制
	private int range = 3;
	// 提示的信息
	private String infoString;
	private Activity mActivity;
	public EditText mEditText;

	// 构造函数
	public EditTextWatcher(Activity activity, EditText text) {
		super();

		this.mActivity = activity;
		this.mEditText = text;
		temp = text.getText().toString();
	}

	// 设置toast提示信息
	public void setInfomation(String infoString, int range) {
		this.range = range;
		this.infoString = infoString;
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if(s != null){
			temp = s;
		}
		
	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	public void afterTextChanged(Editable s) {
		// for some reason , we should substract one
		int textLength = 0;
		try {
			// we should speciafy the encode ->gbk
			textLength = temp.toString().getBytes("gbk").length;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		if (textLength > range) {
			selectionStart = mEditText.getSelectionStart();
			selectionEnd = mEditText.getSelectionEnd();
			// Toast.makeText(EditTextWatcher.this.mActivity, infoString,
			// Toast.LENGTH_SHORT).show();
			ToastUtils.show(EditTextWatcher.this.mActivity, infoString);
			int tempSelection = 0;
			if(selectionStart == 0){
				temp = s.subSequence(0, range-1);
				s.clear();
				s.append(temp);
			}else{
				tempSelection = selectionStart - 1;
				s.delete(selectionStart - 1, selectionEnd);
			}
			
			Log.v(TAG, "输入的信息为:" + s + "infoString" + infoString + "range:"
					+ range);
			mEditText.setText(s);
			mEditText.setSelection(tempSelection);
		}

	}

}
